/**
 * @author yxw
 * date : 2014年1月31日 下午8:15:28 
 */
package com.tzinfo.tzb;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.LocalActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup.MarginLayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.galhttprequest.GalHttpRequest;
import com.galhttprequest.GalHttpRequest.GalHttpLoadTextCallBack;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tzinfo.data.JudgeStatusResult;
import com.tzinfo.data.TztData;
import com.tzinfo.tzb.domain.ActivePic;
import com.tzinfo.tzb.domain.ActivePic.PicData;
import com.tzinfo.tzb.domain.ClassList;
import com.tzinfo.tzb.domain.ClassList.ClassData.ClassSubMenu;
import com.tzinfo.tzb.util.SharedPreferencesTools.TimeCache;
import com.tzinfo.tzb.util.TzbCommonData;
import com.tzinfo.tzb.view.adapter.MyPagerAdapter;
import com.tzinfo.tzt.R;
import com.tzinfo.tzt.util.HttpUtils;
import com.yxw.util.OutLog;
import com.yxw.view.NoScrollListView;
import com.yxw.view.YXWViewPagerIndicator;
import com.yxw.view.adapter.ImageAdapter;
import com.yxw.view.adapter.ImagePagerAdapter;
import com.yxw.view.util.ResFinder;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

public class TzbTabBangActivity extends TzbBaseActivity {
    // UI组件
    private ViewPager pager, pager_images;
    private LinearLayout pagerIndicator2;
    private RelativeLayout layout_top_pager;
    private YXWViewPagerIndicator pagerIndicator;
    private List<View> viewList;
    private TextView textView;
    private ImageView img_no_page_images;

    // 适配器
    private ImageClickPagerAdapter imagePagerAdapter;

    // 数据
    private List<PicData> picDatas;

    public static TzbTabBangActivity acivity;
    private static int bangTab = 0;

    private LocalActivityManager mlam;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tzb_ac_main_bang);
        acivity = this;
        mlam = new LocalActivityManager(this, false);
        mlam.dispatchCreate(savedInstanceState);
        init();
    }

    // 初始化
    private void init() {
        // 加载滚动进入条
        mProgressBar = (ProgressBar) ResFinder.findViewById(this,
                "R.id.progressbar_loding");
        img_no_page_images = (ImageView) ResFinder.findViewById(this,
                "R.id.img_no_page_images");
        pager = (ViewPager) ResFinder.findViewById(this, "R.id.pager");
        pager_images = (ViewPager) ResFinder.findViewById(this,
                "R.id.pager_images");


        pagerIndicator2 = (LinearLayout) ResFinder.findViewById(this,
                "R.id.pagerIndicator2");
        layout_top_pager = (RelativeLayout) ResFinder.findViewById(this,
                "R.id.layout_top_pager");
        LayoutParams params = layout_top_pager.getLayoutParams();
        //使用固定比例图片
        params.height = TztData.widthPixels * 300 / 640;
        layout_top_pager.setLayoutParams(params);
        pagerIndicator = (YXWViewPagerIndicator) ResFinder.findViewById(this,
                "R.id.view_pager_indicator");

        requestPageImages();
        requestInfo();
    }

    // 请求pager图片
    private void requestPageImages() {
        if (ActivePic.dao == null || !ActivePic.dao.isSuccess()) {
            String url = getResources().getString(
                    ResFinder.getR(this, "R.string.tzb_url_ActivePic"));
            GalHttpRequest galHttpRequest = new GalHttpRequest(this, url);
            galHttpRequest.setCacheEnable(false);
            galHttpRequest
                    .startAsynRequestString(new GalHttpLoadTextCallBack() {

                        @Override
                        public void textLoaded(String arg0) {
                            Gson gson = new Gson();
                            java.lang.reflect.Type type = new TypeToken<ActivePic>() {
                            }.getType();
                            ActivePic.dao = gson.fromJson(arg0, type);
                            if (ActivePic.dao.isSuccess()) {
                                iniActivePicViewtPager();
                            }

                        }
                    });
        } else {
            iniActivePicViewtPager();
        }
    }

    public void requestInfo() {
        TimeCache cache = sharedPreferencesTools.getOneDayCache("ClassList");
        if (cache != null && !cache.isOverdue()) {
            Gson gson = new Gson();
            java.lang.reflect.Type type = new TypeToken<ClassList>() {
            }.getType();
            ClassList.dao = gson.fromJson((String) cache.getObj(), type);
        }

        if (ClassList.dao == null || !ClassList.dao.isSuccess()) {
            showProgressBar();
            String url = getResources().getString(R.string.tzb_url_ClassList);
            OutLog.LogE("url", url);
            GalHttpRequest galHttpRequest = new GalHttpRequest(this, url);
            galHttpRequest.setCacheEnable(false);
            galHttpRequest
                    .startAsynRequestString(new GalHttpLoadTextCallBack() {

                        @Override
                        public void textLoaded(String arg0) {
                            Gson gson = new Gson();
                            java.lang.reflect.Type type = new TypeToken<ClassList>() {
                            }.getType();
                            ClassList.dao = gson.fromJson(arg0, type);
                            removeProgressBar();
                            if (ClassList.dao.isSuccess()) {
                                sharedPreferencesTools.saveOneDayCache(
                                        "ClassList", arg0);
                                iniViewtPager();
                            }
                        }
                    });
        } else {
            iniViewtPager();
        }
    }

    private void iniActivePicViewtPager() {
        img_no_page_images.setVisibility(View.GONE);
        List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
        Map<String, Object> map = new HashMap<String, Object>();
        picDatas = ActivePic.dao.getData();
        for (int i = 0; i < picDatas.size(); i++) {
            map = new HashMap<String, Object>();
            map.put("img", picDatas.get(i).getPic_File());
            data.add(map);
        }
        imagePagerAdapter = new ImageClickPagerAdapter(this, data,
                ResFinder.getR(this, "R.layout.item_pager_image"),
                new String[]{"img"}, new int[]{ResFinder.getR(this,
                "R.id.image")});
        pagerIndicator.setViewPager(pager_images, imagePagerAdapter);
    }

    private void iniViewtPager() {
        viewList = new ArrayList<View>();
        LayoutInflater inflater = LayoutInflater.from(this);

        for (int i = 0; i < ClassList.dao.getData().size(); i++) {
            final int tab = i;
            // 初始化pagerIndicator2
            View pagerIndicator2View = inflater.inflate(R.layout.tzb_tabhost_indicator,
                    null);
            LayoutParams params = new LayoutParams(
                    TztData.widthPixels / ClassList.dao.getData().size(),
                    LayoutParams.WRAP_CONTENT);
            pagerIndicator2View.setLayoutParams(params);
            TextView localTextView = (TextView) ResFinder.findViewById(
                    pagerIndicator2View, "R.id.title");
            localTextView.setText(ClassList.dao.getData().get(i).getName());
            if (bangTab == i) {
                localTextView.setSelected(true);
            }
            // 图片
            localTextView.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    View childViewOld = pagerIndicator2.getChildAt(bangTab);
                    TextView textViewOld = (TextView) ResFinder.findViewById(
                            childViewOld, "R.id.title");
                    textViewOld.setSelected(false);
                    bangTab = tab;
                    View childViewNew = pagerIndicator2.getChildAt(tab);
                    TextView textViewNew = (TextView) ResFinder.findViewById(
                            childViewNew, "R.id.title");
                    textViewNew.setSelected(true);
                    pager.setCurrentItem(tab);
                }
            });
            pagerIndicator2.addView(pagerIndicator2View, i);

            // 初始化viewList，用于设置viewPager
            NoScrollListView listView = (NoScrollListView) inflater.inflate(
                    ResFinder.getR(this, "R.layout.tzb_layout_main_bang_list"),
                    null);

            List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
            List<ClassSubMenu> subMenuList = ClassList.dao.getData().get(i)
                    .getSubMenu();
            for (int j = 0; j < subMenuList.size(); j++) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("img", subMenuList.get(j).getPicFile());
                map.put("title", subMenuList.get(j).getName());
                switch (subMenuList.get(j).getForumType()) {
                    case 1:
                        map.put("context", "新闻类板块");
                        break;

                    default:
                        map.put("context", "普通板块");
                        break;
                }

                data.add(map);
            }
            OutLog.LogE("imageAdapter", "设置适配器");

            ImageAdapter imageAdapter = new ImageAdapter(this, data, R.layout.tzb_item_bang,
                    new String[]{"img", "title", "context"}, new int[]{R.id.list_item_image,
                    R.id.list_item_title,
                    R.id.list_item_context});
            listView.setAdapter(imageAdapter);
            listView.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                                        int arg2, long arg3) {

                    TzbCommonData.classSubMenu = ClassList.dao.getData()
                            .get(tab).getSubMenu().get((int) arg3);
                    if (TzbCommonData.classSubMenu.getName().equals("今日头条")) {
                        startActivity(new Intent(TzbTabBangActivity.this,
                                TzbBangForumthreadListActivity2.class));
                        return;
                    } else {
                        Intent intent = new Intent(TzbTabBangActivity.this,
                                TzbBangForumthreadListActivity.class);
                        startActivity(intent);
                    }
                }
            });
            viewList.add(listView);
        }
        // 设置适配器
        pager.setAdapter(new MyPagerAdapter(viewList));
        setViewPagerHeightBasedOnListView(pager,
                (NoScrollListView) viewList.get(bangTab));
        pager.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {

                View childViewOld = pagerIndicator2.getChildAt(bangTab);
                TextView textViewOld = (TextView) ResFinder.findViewById(
                        childViewOld, "R.id.title");
                textViewOld.setSelected(false);
                bangTab = arg0;
                View childViewNew = pagerIndicator2.getChildAt(arg0);
                TextView textViewNew = (TextView) ResFinder.findViewById(
                        childViewNew, "R.id.title");
                textViewNew.setSelected(true);
                // 修改ViewPage高度
                setViewPagerHeightBasedOnListView(pager,
                        (NoScrollListView) viewList.get(arg0));

            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                // TODO Auto-generated method stub

            }
        });
        pager.setCurrentItem(bangTab, true);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    public void setViewPagerHeightBasedOnListView(ViewPager pager,
                                                  NoScrollListView listView) {
        int totalHeight = 0;
        listView.measure(0, 0);
        totalHeight += listView.getMeasuredHeight();
        LayoutParams params = pager.getLayoutParams();
        params.height = 1 + totalHeight;
        ((MarginLayoutParams) params).setMargins(0, 10, 0, 10);
        pager.setLayoutParams(params);
    }


    // 自定义可点击的图片的适配器
    class ImageClickPagerAdapter extends ImagePagerAdapter {

        public ImageClickPagerAdapter(Context context,
                                      List<Map<String, Object>> data, int layoutId, String[] sNmaes,
                                      int[] ids) {
            super(context, data, layoutId, sNmaes, ids);
            // TODO Auto-generated constructor stub
        }

        @Override
        public Object instantiateItem(ViewGroup view, int position) {
            // TODO Auto-generated method stub
            super.instantiateItem(view, position);
            ImageView imageView = (ImageView) ResFinder.findViewById(
                    imageLayout, "R.id.image");
            imageView.setOnClickListener(new MyOnclickListener(position));
            return imageLayout;
        }

        class MyOnclickListener implements OnClickListener {

            int position;

            public MyOnclickListener(int position) {
                this.position = position;
            }

            @Override
            public void onClick(View v) {
                int currentId = position;
                Intent intent = new Intent(TzbTabBangActivity.this,
                        TzbBangActiveWebActivity.class);
                intent.putExtra("title", picDatas.get(currentId).getTitle());
                intent.putExtra("url", picDatas.get(currentId).getUrl());
                startActivity(intent);
            }

        }

    }
}
